package com.bluefuture.modules.app.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bluefuture.common.exception.GlobalException;
import com.bluefuture.common.utils.MailBean;
import com.bluefuture.common.utils.MailUtil;
import com.bluefuture.common.utils.ResultEnum;
import com.bluefuture.modules.app.utils.CodeUtil;
import com.bluefuture.modules.app.utils.EmailUtil;
import com.bluefuture.modules.app.utils.RedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: leo
 * @date: 2019/9/6
 */
@Service
@Slf4j
public class EmailService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MailUtil mailUtil;


    public void sendVerifyCode(String email) {
        String emailCode = CodeUtil.getSmsCode();
        String content="【Huber】Your email verification code: "+emailCode;
        String subject = "Huber";
        MailBean mailBean =new MailBean ();
        mailBean .setToAccount(email);
        mailBean.setSubject(subject );
        mailBean.setContent(content);
        boolean sendResult = mailUtil.sendMailAttachment(mailBean);
        if (sendResult) {
            log.info("邮箱：{}，验证码发送成功", email);
        } else {
            log.error("邮箱：{}，验证码发送失败;", email);
            throw new GlobalException(ResultEnum.SMS_SEND_ERROR);
        }
        redisTemplate.opsForValue().set(RedisConstant.EMAIL_CODE_PREFIX + email, emailCode, 10, TimeUnit.DAYS);
    }

    public void checkVerifyCode(String email, String code) {
        String redisCode = (String) redisTemplate.opsForValue().get(RedisConstant.EMAIL_CODE_PREFIX + email);
        if (redisCode == null || !redisCode.equals(code)) {
            throw new GlobalException(ResultEnum.SMS_CODE_ERROR);
        }
    }

    private String sendSmsByPost(String path, String postContent) {
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setConnectTimeout(10000);
            httpURLConnection.setReadTimeout(10000);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.connect();
            OutputStream os = httpURLConnection.getOutputStream();
            os.write(postContent.getBytes("UTF-8"));
            os.flush();
            StringBuilder sb = new StringBuilder();
            int httpRspCode = httpURLConnection.getResponseCode();
            if (httpRspCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
